using CfgTable;
using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using IQIGame.Onigao.Logic;
using System.Collections.Generic;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class MainCityPlayerAvatarEntity : MainCityRealityEntity
    {
        public override uint MaxStore => 1;

        private MainCityMoveComponent _moveComponent;
        private Dictionary<int, float> _entityDisPrev = new Dictionary<int, float>();
        private Dictionary<int, float> _entityDisNow = new Dictionary<int, float>();
        private float _viewRange;
        /// <summary>
        /// 视野内的实体
        /// </summary>
        public HashSet<MainCityNormalEntity> entitiesInSight = new();

        public override string name => "MainCityPlayerAvatar";
        public override int viewRange => (int)GameMathUtil.Float2LogicValue(_viewRange);
        public override int viewAngle => 360;
        public override float defaultMeterSpeed => 3;
        protected override bool isRecastAgent => true;
        public override CfgPhysicalEntity cfgEntity => TableCenter.physicalEntity.Get(QueryLeaderHero().cfgSkin.LevelEntity);
        public DynMainCityPlayerAvatar dynPlayerAvatarEntity => dynEntity as DynMainCityPlayerAvatar;
        public int manualTrackingEntity { get; internal set; }
        public FormationData defaultFormationData => GameDataCenter.PlayerData.formation.defaultFormationData;
        public override bool isActive => true;

        public void Init(Vector3 defaultBornPoint)
        {
            dynEntity = new DynMainCityPlayerAvatar();

            var pos = GameDataCenter.PlayerData.mainCityData.playerPos;
            if (pos == default)
            {
                pos = defaultBornPoint;
            }
            dynEntity.UpdatePos(pos);

            _moveComponent = AddComponentWithPool<MainCityMoveComponent>(ETComponentType.EntityMove);
            _moveComponent.isPlayerAvatarEntity = true;

            AddComponentWithPool<MainCityAnimationComponent>(ETComponentType.EntityAnimation);
            AddComponentWithPool<EntitySmallPetComponent>(ETComponentType.SmallPetComponent);
            AddComponentWithPool<EntityUIViewComponent>(ETComponentType.EntityUIView);

            _viewRange = MainCityConst.DefaultPlayerViewRadius;
        }

        public HeroData QueryLeaderHero()
        {
            var formation = defaultFormationData;
            foreach (var kv in formation.heros)
            {
                if (kv.Value.cid == formation.captainHeroCid)
                {
                    return kv.Value.heroData;
                }
            }
            return null;
        }

        protected override void CreateTransformAgent()
        {
            _transform = ClassPool.Get<TransformAgent>();
        }

        public override void OnEntityBirth()
        {
            base.OnEntityBirth();
        }

        public void MoveStep(float angle, float power)
        {
            _moveComponent.MoveStep(angle, power);
        }

        public void StopMove(bool isImmediately)
        {
            _moveComponent.StopMove(isImmediately);
        }

        protected override string GetEntityLoadPath()
        {
            return PathConstant.GetCharacterLevelPrefabPath(cfgEntity.EntityAsset);
        }

        public void EntityDisNowToPrev()
        {
            _entityDisPrev.Clear();
            foreach (var kv in _entityDisNow)
            {
                _entityDisPrev.Add(kv.Key, kv.Value);
            }
            _entityDisNow.Clear();
        }

        public void UpdateEntityDis(int entityId, float sqrDistance)
        {
            _entityDisNow.Add(entityId, sqrDistance);
        }

        /// <summary>
        /// 获取上一次指定实体和英雄的距离（仅针对触发器有效）
        /// </summary>
        public float GetPrevEntityDisFromMe(int entityId)
        {
            if (_entityDisPrev.TryGetValue(entityId, out float sqrDis))
            {
                return sqrDis;
            }
            return -1;
        }

        public override ServiceNonLevel TryTriggerService(MainCityTriggerType triggerType, out bool anyExecDone, object dynamicObjParam = null, TrigValueTypeParam dynamicValueTypePram = default)
        {
            anyExecDone = false;
            return null;
        }

        public void SetAsDynObstacle()
        {
            ObstacleInfo obstacle = new ObstacleInfo();
            obstacle.isStatic = false;
            obstacle.w = 30;
            obstacle.height = 100;
            ObstacleId = navigationCtrl.AddObstacle(transform.position, Vector3.forward, obstacle, defaultMeterSpeed);
        }

        /// <summary>
        /// 设置玩家视野，单位米
        /// </summary>
        /// <param name="meter"></param>
        public void SetViewRange(float meter)
        {
            _viewRange = meter;
        }

        /// <summary>
        /// 获取玩家视野，单位米
        /// </summary>
        public float GetViewRange()
        {
            return _viewRange;
        }

        /// <summary>
        /// 刷新玩家化身的模型（队长英雄的模型）
        /// </summary>
        public async UniTask RefreshAvatarModel()
        {
            TryHideEntity();
            await ReLoadModel();
            MainCityModule.Instance.mainController.regionCtrl.cameraCtrl.CharacterFllowLook(transform, transform);
        }

        public override void OnReset()
        {
            base.OnReset();
            _moveComponent = null;
            _entityDisPrev.Clear();
            _entityDisNow.Clear();
            entitiesInSight.Clear();
            _viewRange = 0;
        }
    }
}